<template>
  <div class="workflow-editor">
    <div class="editor-toolbar">
      <el-button-group>
        <el-button size="small" @click="formatJson">
          <el-icon><Operation /></el-icon>
          格式化
        </el-button>
        <el-button size="small" @click="validateJson">
          <el-icon><Check /></el-icon>
          验证
        </el-button>
      </el-button-group>
    </div>

    <div class="editor-container">
      <el-input
        v-model="content"
        type="textarea"
        :rows="15"
        :autosize="{ minRows: 15, maxRows: 30 }"
        @change="handleChange"
      />
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, watch } from 'vue'
import { ElMessage } from 'element-plus'
import { Operation, Check } from '@element-plus/icons-vue'

const props = defineProps<{
  modelValue: string
}>()

const emit = defineEmits(['update:modelValue'])

const content = ref(props.modelValue)

// 监听值变化
watch(() => props.modelValue, (newValue) => {
  if (newValue !== content.value) {
    content.value = newValue
  }
})

// 处理内容变化
const handleChange = (value: string) => {
  content.value = value
  emit('update:modelValue', value)
}

// 格式化 JSON
const formatJson = () => {
  try {
    const obj = JSON.parse(content.value)
    content.value = JSON.stringify(obj, null, 2)
    emit('update:modelValue', content.value)
    ElMessage.success('格式化成功')
  } catch (error) {
    ElMessage.error('无效的 JSON 格式')
  }
}

// 验证 JSON
const validateJson = () => {
  try {
    JSON.parse(content.value)
    ElMessage.success('JSON 格式正确')
  } catch (error) {
    ElMessage.error('无效的 JSON 格式')
  }
}
</script>

<style scoped lang="scss">
.workflow-editor {
  .editor-toolbar {
    margin-bottom: 12px;
  }

  .editor-container {
    :deep(.el-textarea__inner) {
      font-family: 'Monaco', 'Menlo', 'Ubuntu Mono', 'Consolas', monospace;
      font-size: 14px;
      line-height: 1.5;
      padding: 12px;
    }
  }
}
</style>
